package com.apes.scm.masterdata.area.service;

import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.Model;
import com.apes.framework.jpa.repository.CustomRepository;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.scm.masterdata.area.model.BusinessCircle;
import com.apes.scm.masterdata.area.model.BusinessCircleArea;
import com.apes.scm.masterdata.area.repository.AreaRepository;
import com.apes.scm.masterdata.area.repository.BusinessCircleAreaRepository;
import com.apes.scm.masterdata.area.repository.BusinessCircleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Title: BusinessCircleService
 * @Description: 定义商圈信息
 * @author: ZhengZeXian
 * @create: 2022/2/16 16:42
 */
@Service("businessCircleService")
public class BusinessCircleService extends DomainService {

    @Autowired
    private BusinessCircleRepository circleRepository;
    @Autowired
    private BusinessCircleAreaRepository circleAreaRepository;

    /**
     * 创建
     * @param request
     * @return
     */
    public BusinessCircle create(SimpleRequest request) {
        BusinessCircle circle = request.getO(BusinessCircle.class);
        writeItemArea(circle.getBusinessCircleAreas());
        return circleRepository.saveAndFlush(circle);
    }


    /**
     * 功能: 修改
     * @param request
     * @return
     */
    public BusinessCircle update(SimpleRequest request) {
        isVaild(request, circleRepository);
        BusinessCircle circle = request.getO(BusinessCircle.class);
        writeItemArea(circle.getBusinessCircleAreas());
        return circleRepository.saveAndFlush(circle);
    }

    /**
     * 功能：删除商圈
     */
    public BusinessCircle delete(SimpleRequest request) {
        isVaild(request, circleRepository);
        BusinessCircle circle = request.getO(BusinessCircle.class);
        circleAreaRepository.deleteAll(circle.getBusinessCircleAreas());
        return circleRepository.saveAndFlush(circle);
    }

    /**
     * 根据前端区域编码写入对应区域实体
     * @param itemList
     */
    public List<BusinessCircleArea> writeItemArea(List<BusinessCircleArea> itemList){
        itemList.forEach(item -> {
            item.setArea(SpringManager.getBean(AreaRepository.class).findOne(item.getArea_id()));
        });
        return itemList;
    }

    /**
     * 验证数据合法性
     * @param request 请求参数
     * @param repository 当前的数据层访问参数
     * @return
     */
    private Model isVaild(SimpleRequest request, CustomRepository repository){
        Model oldModel = (Model)  repository.findOne((String) request.get("id"));
        if (oldModel == null) throw new RuntimeException("商圈【" + request.get("id") + "】在系统中不存在。");
        if (oldModel.getVersion() != (int) request.get("version")) throw new RuntimeException("记录已更新或已删除，请重新提交！");
        return oldModel;
    }

}

